package com.wty.zuul.filters;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.netflix.zuul.http.ServletInputStreamWrapper;
import com.wty.zuul.rsa.RsaKeys;
import com.wty.zuul.service.RsaService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @Author:wangtianyu
 * @Date：Created on 2020/5/9 0009 20:21
 */
@Slf4j
@Component
public class GoodFilterWty extends ZuulFilter {

    @Autowired
    private RsaService rsaService;

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return FilterConstants.PRE_DECORATION_FILTER_ORDER + 1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @SneakyThrows
    @Override
    public Object run() throws ZuulException {
        // 我们需要做的事情
        // 1.获取请求体（密文）

        // 获取HttpServletRequest
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        // 拿取密文
        ServletInputStream inputStream = request.getInputStream();
        String encryptData = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
        log.info("加密后的数据：\n{}",encryptData);
        // 2.解密请求体
        String decryptData = rsaService.RSADecryptDataPEM(encryptData, RsaKeys.getServerPrvKeyPkcs8()); // 解密，返回解密后的数据
        log.info("解密后的数据：\n{}",decryptData);
        // 3.重新封装请求数据，解密的数据
        final byte[] reqBodyBytes = decryptData.getBytes(); // 将解密后的数据转成二进制
        // 设置请求 数据
        currentContext.setRequest(new HttpServletRequestWrapper(request) {
            @Override
            public ServletInputStream getInputStream() throws IOException {
                // 数据重新封装，封装的是解密后的数据
                return new ServletInputStreamWrapper(reqBodyBytes);
            }

            // 数据的长度
            @Override
            public int getContentLength() {
                return reqBodyBytes.length;
            }
            @Override
            public long getContentLengthLong() {
                return reqBodyBytes.length;
            }
        });

        // 设置请求头
        currentContext.addZuulRequestHeader("Content-Type", "application/json" + ";charset=UTF-8");
        return null;
    }
}
